package org.redis.cluster.event;

import java.util.Collection;

import org.apache.commons.collections.CollectionUtils;
import org.redis.cluster.RedisCluster;
import org.redis.cluster.extension.ExtensionLoader;
import org.redis.cluster.plugin.Plugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultEventPusher implements EventPusher,Plugin {
	
	protected final Logger logger=LoggerFactory.getLogger(getClass());
	
	private RedisCluster redisCluster;
	private ExtensionLoader extensionLoader;
	private Collection<EventListener> listeners;

	@Override
	public void init(RedisCluster redisCluster) {
		this.redisCluster=redisCluster;
		this.extensionLoader=redisCluster.getExtensionLoader();
		this.listeners=initListeners();
	}

	@Override
	public boolean push(Event event) {
		if(CollectionUtils.isEmpty(listeners)) {
			return false;
		}
		
		if(logger.isDebugEnabled()) {
			logger.debug("推送事件 - {}",event);
		}
		
		boolean result=false;
		for(EventListener listener:listeners) {
			if(listener.isSupport(event)) {
				if(logger.isDebugEnabled()) {
					logger.debug("推送事件 - {} -> {}",event,listener);
				}
				
				try {
					listener.onEvent(event);
				}
				catch(Exception e) {
					if(logger.isErrorEnabled()) {
						logger.error("",e);
					}
				}
				
				result=true;
			}
		}
		
		return result;
	}
	
	@Override
	public void destroy() {
	}
	
	protected Collection<EventListener> initListeners() {
		return extensionLoader.load(EventListener.class);
	}
}